package com.home.free.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 时间准换的工具类
 * @author gaotianjie
 *
 */
public class DateUtil {
    public static final String YY_DD_MM = "yyyy-MM-dd";

    /**
     * 获取当前时间的年月日
     *
     * @return
     */
    public static String nowToString() {
        //创建一个Calendar对象
        Calendar calendar = Calendar.getInstance();

        return getYyDdMm(calendar);
    }

    /**
     * 获取秒的时间戳
     * @return
     */
    public static Integer getSecondTime() {
        Calendar calendar = Calendar.getInstance();
        return (int) calendar.getTimeInMillis() / 1000;
    }

    /**
     * 获取毫秒的时间戳
     * @return
     */
    public static Long getMilliSecondTime() {
        Calendar calendar = Calendar.getInstance();
        return calendar.getTimeInMillis();
    }


    /**
     * 获取指定时间的年月日
     * @param time
     * @return
     */
    public static String timeToString(Long time) throws DateTimeParseException {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(time));

        return getYyDdMm(calendar);
    }



    /**
     * 根据指定日期获取秒的时间戳
     *
     * @param dateTime
     * @return
     * @throws ParseException
     */
    public static int stringToTime(String dateTime) throws ParseException {
        DateFormat df = new SimpleDateFormat(YY_DD_MM);
        Date date = df.parse(dateTime);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        //单位为秒
        return (int) cal.getTimeInMillis() / 1000;
    }

    /**
     * 把指定的时间对象转为时间戳
     *
     * @param calendar
     * @return
     */
    private static String getYyDdMm(Calendar calendar) {
        //获得年
        int year=calendar.get(Calendar.YEAR);
        //获得月
        int month=calendar.get(Calendar.MONTH) + 1;
        //获得日
        int date=calendar.get(Calendar.DAY_OF_MONTH);

        return String.format("%d-%d-%d", year, month, date);
    }
}
